package com.blog.utils;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

import com.mchange.v2.c3p0.ComboPooledDataSource;

import java.sql.Statement;
import java.sql.Connection;


public class C3p0DataSourceUtil {

	private static ComboPooledDataSource dataSource = new ComboPooledDataSource();

	private  static ThreadLocal<Connection> tr = new ThreadLocal<Connection>();
	
	
	/*
	 * 使用c3p0-config.xml配置文件后，无需使用静态块
	 * static{
		Properties pro=new Properties();
		try {
			pro.load(C3p0DataSourceUtil.class.getResourceAsStream("/dataSource.properties"));
			dataSource.setDriverClass(pro.getProperty("dbDriver"));
			dataSource.setUser(pro.getProperty("dbUser"));
			dataSource.setPassword(pro.getProperty("dbPassword")) ;
			dataSource.setJdbcUrl(pro.getProperty("jdbcUrl"));
		   
			dataSource.setInitialPoolSize(Integer.valueOf(pro.getProperty("intPool")));
		
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}*/
	
	
    public static Connection getConnection(){
		Connection con = null;
		try {
			if (tr.get() == null) {
				con = dataSource.getConnection();
				tr.set(con);
			} else {
				con = tr.get();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return con;
    }

    	
   
    
    
    public static void close(ResultSet rs,Statement stat,Connection con){
    	
    	try {
    		rs.close();
			stat.close();
			con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    }
    public static void close(Statement stat,Connection con){
    	
    	try {
    		
			stat.close();
			con.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	
    }
    
    public static void close(){
    	try {
			getConnection().close();
			tr.set(null);//清除con
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
}
